<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="css/style.css">
    <style>
        body {
            font-family: 'Open Sans', sans-serif;
            font-size: 16px;
            line-height: 1.8;
            background-color: #fff;
            margin: 0 20px;
        }

        .container {
            background-color: #fff;
        }
    </style>
</head>

<body>
    <div class="container">
        <h1>Word Counter</h1>
        <label for="text">Enter some text below:</label>
        <textarea name="in" id="text" rows="10" cols="60"></textarea>
        <div id="stat">
            <p>You've written <span class="highlight">0 words</span>
                and <span class="highlight">0 characters</span>.</p>
        </div>
    </div>

    <script>
        class WordCounter {
            constructor(inputText) {
                this.inputText = inputText;
                this.inputText.addEventListener('input', () => {
                    this.count();
                })
            }
            count() {
                let wordStat = this.getWordStat(this.inputText.value.trim())
                this.emitEvent(wordStat)
            }
            emitEvent(wordStat) {
                // Create count Event
                let countEvent = new CustomEvent('count', {
                    bubbles: true,
                    cancelable: true,
                    detail: { wordStat }
                })
                this.inputText.dispatchEvent(countEvent)
            }
            getWordStat(text) {
                let words = text.split(/\s+/).filter(word => word.length > 0)
                let characters = text.length
                return {
                    words: words.length,
                    characters
                }
            }
        }


        const inputText = document.querySelector('#text');
        const statElem = document.querySelector('#stat');

        // create a new instance of Word Counter
        new WordCounter(inputText);

        // render the 
        const render = (e) => {
            statElem.innerHTML = `<p>You've written <span class="highlight">${e.detail.wordStat.words} words</span> 
        and <span class="highlight">${e.detail.wordStat.characters} characters</span>.</p>`;
        }

        inputText.addEventListener('count', render);
    </script>
</body>

</html>